// 加载环境变量
require('dotenv').config();

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var cors = require('cors');

// 导入数据库连接
require('./model/db');

var expressJWT = require("express-jwt")
const { router: indexRouter, setupWebSocket } = require('./routes/index');
var usersRouter = require('./routes/users');
var lxtRouter = require('./routes/lxt');
var difyRouter = require('./routes/dify');
var difyRouter = require('./routes/dify');
var documentRouter = require('./routes/documents');
// var apiRouter = require('./routes/api'); // <--- 假设你会创建一个新的api.js文件

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(cors({
  origin: ['http://localhost:5173', 'http://localhost:3001', 'http://localhost:9000'],
  credentials: true
}));
app.use(logger('dev')); // 保持一个
app.use(express.json()); // 保持一个
app.use(express.urlencoded({ extended: true })); // 保持一个，并设置为true
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));
app.use('/api/uploads', express.static(path.join(__dirname, 'public/uploads')));
// 课程文件静态服务
app.use('/uploads/videos', express.static(path.join(__dirname, 'public/uploads/videos')));
app.use('/uploads/course-images', express.static(path.join(__dirname, 'public/uploads/course-images')));
app.use('/uploads/course-files', express.static(path.join(__dirname, 'public/uploads/course-files')));
app.use('/api/uploads/videos', express.static(path.join(__dirname, 'public/uploads/videos')));
app.use('/api/uploads/course-images', express.static(path.join(__dirname, 'public/uploads/course-images')));
app.use('/api/uploads/course-files', express.static(path.join(__dirname, 'public/uploads/course-files')));


// 管理员路由的session认证中间件
const adminAuthMiddleware = (req, res, next) => {
  // 检查是否是管理员路由
  const adminRoutes = [
    '/dashboard/stats',
    '/dashboard/order-trend',
    '/dashboard/revenue',
    '/api/courses',
    '/api/teachers',
    '/api/upload',
    '/api/addteachers',
    '/api/students',
    '/api/schedules',
    '/orders',
    '/students',
    '/api/upload-course-video',
    '/api/upload-course-images',
    '/api/add-course'
    // 移除了 '/logins'，因为登录页面不应该需要认证
  ];

  const isAdminRoute = adminRoutes.some(route => req.path.startsWith(route)) ||
    /^\/api\/teachers\/.*$/.test(req.path) ||
    /^\/api\/students\/.*$/.test(req.path) ||
    /^\/api\/courses\/.*$/.test(req.path) ||
    /^\/api\/schedules\/.*$/.test(req.path) ||
    /^\/orders\/.*$/.test(req.path) ||
    /^\/students\/.*$/.test(req.path);

  console.log(`AdminAuthMiddleware - Path: ${req.path}, Method: ${req.method}, IsAdminRoute: ${isAdminRoute}`);

  if (isAdminRoute) {
    // 对于管理员路由，检查Authorization头
    const authHeader = req.headers.authorization;
    if (!authHeader) {
      console.log(`管理员路由缺少Authorization头: ${req.path}`);
      return res.status(401).json({
        success: false,
        message: '缺少认证信息'
      });
    }
    
    // 简单的token检查（这里可以根据需要添加更复杂的验证）
    const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : authHeader;
    if (!token) {
      console.log(`管理员路由token无效: ${req.path}`);
      return res.status(401).json({
        success: false,
        message: '认证信息无效'
      });
    }
    
    console.log(`管理员路由认证通过: ${req.path}`);
    return next();
  }

  // 对于其他路由，继续到下一个中间件（JWT认证）
  console.log(`继续到JWT认证: ${req.path}`);
  return next();
};

// 使用管理员认证中间件
app.use(adminAuthMiddleware);

// JWT认证中间件 (用于非管理员路由)
app.use(
  expressJWT({
    secret: "123", //生成token的口令
    algorithms: ["HS256"], //固定的加密算法
  }).unless({
    path: [
      // 登录相关路由
      "/lxt/login", 
      "/lxt/register", 
      "/lxt/send-reset-code",
      "/lxt/verify-reset-code",
      "/lxt/reset-password",
      "/lxt/send-verification-code",  // 验证码发送路由
      "/lxt/shuidi-login",           // 水滴聚合登录
      "/lxt/shuidi-callback",        // 水滴聚合回调
      "/lxt/shuidi-debug",           // 诊断路由
      "/lxt/test-email",             // 测试邮箱
      "/lxt/test-sms",               // 测试短信
      "/favicon.ico",              // 网站图标
      "/logins", // 添加这个登录路由到白名单
      // 管理员路由
      "/dashboard/stats",
      "/dashboard/order-trend",
      "/dashboard/revenue",
      "/api/courses",
      "/api/teachers",
      "/api/upload",
      "/api/addteachers",
      "/api/students",
      "/api/schedules",
      "/orders",
      "/students",
      "/hoemd",
      "/api/upload-course-video",
      "/api/upload-course-images",
      "/api/add-course",
      /^\/api\/teachers\/.*$/,
      /^\/api\/students\/.*$/,
      /^\/api\/courses\/.*$/,
      /^\/api\/schedules\/.*$/,
      /^\/orders\/.*$/,
      /^\/students\/.*$/,
      // Dify AI 路由
      /^\/dify\/.*$/,
      /^\/api\/dify\/.*$/,
      // 文档生成路由
      /^\/api\/documents\/.*$/,
      // 静态文件路由
      "/uploads",
      "/api/uploads",
      "/uploads/videos",
      "/uploads/course-images",
      "/uploads/course-files",
      "/api/uploads/videos",
      "/api/uploads/course-images",
      "/api/uploads/course-files",
      // 健康检查路由
      "/api/dify/health",
      "/api/dify/supported-types",
      // 静态资源
      /^\/public\/.*/,
      /^\/stylesheets\/.*/,
      /^\/image\/.*/,
      /^\/vite\.svg$/,
      /^\/react\.svg$/
    ], //path表示白名单 如果项目中某个路由不需要认证 写入到白名单中 ，注意路由一定要写完整
  })
)


app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/lxt', lxtRouter);
app.use('/api/dify', difyRouter);  // Dify AI 聊天路由
app.use('/api/documents', documentRouter);  // 文档生成路由
app.use('/api', indexRouter);  // 添加 /api 前缀
// app.use('/api', apiRouter); // <--- 在这里注册你的新API路由

// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   next(createError(404, `Not Found - ${req.originalUrl}`)); // 包含原始URL
// }); 

// error handler
app.use((err, req, res, next) => {
  console.error('全局错误处理:', err);

  // 处理JWT认证错误
  if (err.name === 'UnauthorizedError') {
    console.error('JWT认证失败:', {
      path: req.path,
      method: req.method,
      headers: req.headers,
      body: req.body
    });

    return res.status(401).json({
      code: 401,
      message: '认证失败',
      error: err.message
    });
  }

  res.status(500).json({
    code: 500,
    message: '服务器错误',
    error: err.message
  });
});
// 创建 HTTP 服务器
const server = require('http').createServer(app);

// 设置 WebSocket
setupWebSocket(server);

// 启动服务器
const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log(`Dify Chatflow API地址: ${process.env.DIFY_API_URL || 'http://127.0.0.1/v1'}`);
  console.log(`应用ID: ${process.env.DIFY_APP_ID || 'vKisALZl7SmxNc3B'}`);
  console.log(`API密钥状态: ${process.env.DIFY_API_KEY ? '已配置' : '未配置'}`);
  if (!process.env.DIFY_API_KEY) {
    console.log('⚠️  警告: 未配置DIFY_API_KEY，Dify API调用将失败，使用备用方案');
  }
});

module.exports = app;
